package com.school.edupoint.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync  // 启用异步支持
public class AsyncConfig {

    @Bean(name = "taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // 核心线程数（保持活跃的线程数）
        executor.setCorePoolSize(10);
        
        // 最大线程数（当队列满时，可以创建的最大线程数）
        executor.setMaxPoolSize(50);
        
        // 队列容量（当线程数达到核心线程数时，新任务放入队列等待）
        executor.setQueueCapacity(1000);
        
        // 线程名前缀（方便日志追踪）
        executor.setThreadNamePrefix("Async-DB-Update-");
        
        // 拒绝策略（当线程池和队列都满时如何处理新任务）
        // CallerRunsPolicy：由调用线程（提交任务的线程）直接执行该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        // 初始化
        executor.initialize();
        
        return executor;
    }
    

}